<template>
    <div>
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="漫画名">
                    <el-input type="text" placeholder="请输入漫画名" v-model="queryForm.mediaTitle" size="small" ></el-input>
                </el-form-item>
                <el-form-item label="作 者" >
                    <el-input type="text" placeholder="输入昵称" v-model="queryForm.mediaAuthor" size="small"></el-input>
                </el-form-item>
                <el-form-item label="上传者昵称" >
                    <el-input type="text" placeholder="输入昵称" v-model="queryForm.nickname" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
            :data="userList"
            v-loading="loading"
            border
            fit
            :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
            :cell-style="{padding:'5px 0px'}"
            @selection-change="handleSelectionChange"
            style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px" :selectable="checkSelectable"></el-table-column>
                <el-table-column label="封 面" align="center" width="80">
                    <template slot-scope="scope">
                        <div style="display: flex; justify-content: center;">
                            <el-image 
                                :src="'/imgs/cover' + scope.row.coverPath"
                                style="width: 80px; height: 80px"
                                fit="contain" 
                            ></el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="漫画名"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.mediaTitle }}
                    </template>
                </el-table-column>
                <el-table-column label="作 者"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.mediaAuthor }}
                    </template>
                </el-table-column>
                <el-table-column label="上传者昵称"  align="center" width="240">
                    <template slot-scope="scope">
                    {{ scope.row.nickname }}
                    </template>
                </el-table-column>
                <el-table-column label="漫画简介" align="center">
                    <template slot-scope="scope">
                        <el-tooltip 
                            effect="dark" 
                            :content="scope.row.mediaInfo" 
                            placement="top"
                            >
                            <div class="text-ellipsis-multi">
                                {{ scope.row.mediaInfo }}
                            </div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column label="操 作" align="center" width="300">
                    <template slot-scope="scope">
                        <el-button size="small" type="success" plain icon="el-icon-s-operation" @click="toMedia(scope.row.id)">章节管理</el-button>
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                    :current-page="queryForm.pageNum" 
                    :page-size="queryForm.pageSize"
                    :total="total"
                    :page-sizes="[10,20,50,100]"
                    layout="total,sizes,prev,pager,next"
                    @current-change='handleCurrentChange'
                    @size-change='handleSizeChange'>
                </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show"  width="42%">
            <el-form :model="submitForm" :inline="true" label-width="120px" :rules='rules' ref="submitForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="封面" prop="coverPath">
                            <el-upload
                            class="cover-uploader boxCardUploadImg "
                            action="/admin-api/file/upload/cover"
                            :data="{ userId: uploaderId}"
                            :show-file-list="false"
                            :on-success="handleCoverSuccess"
                            :headers="headers"
                            name="file"
                            :before-upload="beforeCoverUpload"
                            :on-progress="uploadCoverProcess">
                            <img v-if="'/imgs/cover/' + imageUrl" :src="'/imgs/cover/' + imageUrl" class="cover">
                            <i v-else class="el-icon-plus cover-uploader-icon"></i>
                            <i class="el-icon-edit" ></i>
                            </el-upload>
                            <el-progress :style="progressStyle" :text-inside="true" :stroke-width="16" :percentage="loadProgress" :status="progressStatus"></el-progress>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="漫画名" prop="mediaTitle">
                            <el-input type="text" placeholder="请输入漫画名" v-model="submitForm.mediaTitle"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="作 者" prop="mediaAuthor">
                            <el-input type="text" placeholder="请输入作者" v-model="submitForm.mediaAuthor"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="精选" prop="curation">
                            <el-switch v-model="submitForm.curation" active-value="1" inactive-value="0"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="漫画简介" prop="mediaInfo">
                            <el-input type="textarea" placeholder="请输入漫画简介" 
                            :rows="4" :autosize="{ minRows: 4, maxRows: 8 }" 
                            style="width:550px;"
                            v-model="submitForm.mediaInfo"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="dialog-footer" slot="footer" style="margin-right:40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { selectAll,getCollection,addCollection,updateCollection,delCollection } from '@/api/collection'
    export default {
        name:'Comic',
        data(){
            return{
                loading: true,
                userId:this.$Cookie.get("userId"),
                submitForm:{},
                title:"新增",
                show:false,
                total:120,
                queryForm:{
                    mediaType:1,
                    pageNum:1,
                    pageSize:10
                },
                selectList:[],
                userList:[],
                coverFileName:null,
                comicFileName:null,
                fileList:[],
                imageUrl:'default.jpg',
                comicUrl:'',
                headers:{
                    Authorization: 'Bearer ' + this.$Cookie.get('login-token')
                },
                loadProgress: 0,
                progressStatus:null,
                progressStyle: "margin-top:5px;opacity: 0;",
                uploaderId: 100001,
                rules:{
                    mediaTitle:[
                        {required:true,message:'请输入漫画名',trigger:'blur'},
                        {min:1,max:16,message:'长度必须在1-16之间',trigger:'blur'}
                    ],
                    mediaAuthor:[
                        {required:true,message:'请输入作者',trigger:'blur'},
                        {min:1,max:16,message:'长度必须在1-16之间',trigger:'blur'}
                    ],
                    mediaPath:[
                        {required:true,message:'请上传漫画文件',trigger:'blur'}
                    ]    
                }
            }
        },
        //创建网页后查询调用数据
        created(){
            this.getList()
        },
        methods:{
            //调用接口提交数据 - 进行添加和编辑操作的弹窗
            handleSubmit(){
                this.$refs['submitForm'].validate((valid)=>{
                    this.submitForm.mediaType = 1
                    this.fileList = []
                    if(valid){
                        if(this.submitForm.id){
                            this.submitForm.uploaderId = this.uploaderId
                            this.submitForm.updateBy = this.$Cookie.get("username")
                            updateCollection(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }else{
                            this.submitForm.uploaderId = 100001
                            this.submitForm.createBy = this.$Cookie.get("username")
                            addCollection(this.submitForm).then(res=>{
                                this.show = false
                                this.getList()
                                this.submitForm = {}
                            }).catch(err=>{
                                console.log(err)
                            })
                        }
                        
                    }
                })
            },
            //重置搜索
            handleReset(){
                this.queryForm = {
                    mediaType:1,
                    pageNum:1,
                    pageSize:10
                }
                this.getList()
            },
            //按条件搜索
            handleSearch(){
                this.queryForm.mediaType = 1
                this.queryForm.pageNum = 1
                this.queryForm.pageSize = 10
                this.getList()
            },
            //修改每页大小
            handleSizeChange(pageSize){
                this.queryForm.pageSize = pageSize
                this.queryForm.pageNum = 1
                this.getList()
            },
            //当前页修改
            handleCurrentChange(pageNum){
                this.queryForm.pageNum = pageNum
                this.getList()
            },
            //调用接口分页查询用户数据
            getList(){
                this.loading = true
                selectAll(this.queryForm).then(res=>{
                    this.userList = res.data.records
                    this.total = res.data.total
                    this.loading = false
                }).catch(err=>{})
                
            },
            //删除 - 调用接口删除记录
            handleDelete(ids){
                this.$confirm("你确定删除id为"+ids+"的记录吗？","提示",{
                    cancelButtonText:"取消",
                    confirmButtonText:"确定",
                    type:"warning"
                }).then(()=>{
                    //调接口删除
                    delCollection(ids).then(res => {
                        //提示删除成功
                        this.$message("删除成功")
                        //刷新列表
                        this.getList()
                    }).catch(err=>{
                        console.log(err)
                    })
                }).catch(()=>{})
            },
            //添加 - 打开添加弹窗
            handleAdd(){
                this.show = true
                this.title = "新增"
                this.imageUrl = 'default.jpg'
                this.comicUrl = ''
                this.uploaderId = 100001
                this.submitForm={
                    mediaPath:'',
                }
                this.address={}
            },
            //取消 - 关闭弹窗
            handleCancel(){
                this.show = false
            },
            //编辑 - 打开编辑弹窗
            handleEdit(id){
                getCollection(id).then(res=>{
                    //调接口获取最新数据
                    this.title = "编辑"
                    this.show = true
                    this.submitForm = res.data
                    this.imageUrl = res.data.coverPath
                    this.comicUrl = res.data.mediaPath
                    this.uploaderId = res.data.uploaderId
                }).catch(err=>{
                    console.log(err)
                })
                
            },
            //批量删除
            handleBatchDelete(){
                if(this.selectList){
                    let ids = this.selectList.map(o => {return o.id})
                    console.log('ids---------->',ids)
                    this.handleDelete(ids)
                }
            },
            //多选
            handleSelectionChange(val){
                this.selectList = val;
            },
            //选择时，如果为自己id则不能选中
            checkSelectable(row) {
                return row.id != this.userId
            },
            //上传前调用函数
            beforeCoverUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!isJPG) {
                    this.$message.error('上传封面只能是 JPG 或 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 10MB!');
                }
                return isJPG && isLt2M;
            },
            //上传封面进度
            uploadCoverProcess(event, file, fileList) {
                this.progressStyle="margin-top:5px;opacity: 1;",
                this.loadProgress = parseInt(event.percent);
                if (this.loadProgress >= 100) {
                    this.progressStatus = "success"
                    this.loadProgress = 100
                    setTimeout( () => {this.progressStyle="margin-top:5px;opacity: 0;";this.progressStatus = null}, 1000) 
                }
            },
            //封面上传成功调用函数
            handleCoverSuccess(res, file) {
                this.coverFileName = res.data
                this.imageUrl = this.coverFileName;
                this.submitForm.coverPath = this.coverFileName
            },
            //时间格式化
            formatDate(value,format) {
                return parseTime(new Date(value),format)
            },
            toMedia(id){
                this.$router.push({
                    name: 'MediaComic',
                    query: {collectionId: id}
                })
            }
        }
    }
</script>

<style scoped>
    .el-form-item{
        margin: 10px;
    }
    .address-form .el-select .el-input {
        border-color: #409EFF;
        width: 50px;
    }
    .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 20px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .cover-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .cover {
    width: 120px;
    height: 180px;
    border-radius: 20px;
    display: block;
  }
  
.boxCardUploadImg {
  width: 120px;
  height: 180px;
  border-radius: 20px;
  position: relative;
}
.boxCardUploadImg:hover {
  cursor: pointer;
}
.boxCardUploadImg:hover::after {
  content: '';
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 0;
  height: 100%;
  top: 0px;
  width: 100%;
  z-index: 99;
  border-radius: 20px;
}

.boxCardUploadImg i {
  display: none;
}
.boxCardUploadImg:hover i {
  position: absolute;
  font-size: 48px;
  display: initial;
  z-index: 999;
  color: #fff;
  top: 65px;
  left: 34px;
}
/* 两行省略 + hover 显示全部 */
.text-ellipsis-multi {
  display: -webkit-box;
  -webkit-line-clamp: 3;  /* 限制行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 4.5em;  /* 2行 x 1.5行高 */
  cursor: pointer;
}

/* 调整 tooltip 最大宽度 */
.el-tooltip__popper {
  max-width: 400px;
  word-break: break-word;
}
</style>